package generic.swing.tabs;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

/**
 * A tab with both a label, and a close button.
 *
 * Adapted from http://java.sun.com/docs/books/tutorial/uiswing/examples/components/TabComponentsDemoProject/src/components/ButtonTabComponent.java
 * @author Adam Scarr <scarr.adam@gmail.com>
 */
public class Tab extends JPanel {
    private JTabbedPane pane;

    public Tab(String name, final JTabbedPane pane) {
        super(new FlowLayout(FlowLayout.LEFT, 0, 0));
        this.pane = pane;

        setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));

        JLabel label = new JLabel(name);
        //label.
        label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
        add(label);

        final JButton closeButton = new TabButton();
        closeButton.setMargin(new Insets(0, 0, 0, 0));
        closeButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int i = pane.indexOfTabComponent(Tab.this);

                if (i != -1) {
                    pane.remove(i);
                }

            }
        });
        closeButton.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 2));
        add(closeButton);

        setOpaque(false);

    }
}
